<!DOCTYPE html>
<html lang="zh">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
  <title>题目管理</title>
  <style>
    /* 基础样式 */
    * {
      box-sizing: border-box;
      font-family: 'Segoe UI', sans-serif;
    }

    body {
      background: linear-gradient(to bottom right, #e3f2fd, #f5f7fa);
      margin: 0;
      padding: 2rem;
      min-height: 100vh;
    }

    .container {
      max-width: 1200px;
      margin: 0 auto;
      background: white;
      border-radius: 1.5rem;
      box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
      overflow: hidden;
      padding: 2rem;
    }

    h1 {
      color: #1a73e8;
      margin-bottom: 1.5rem;
    }

    a.back-link {
      display: inline-block;
      margin-bottom: 1.5rem;
      color: #1a73e8;
      text-decoration: none;
      font-weight: 500;
    }

    a.back-link:hover {
      text-decoration: underline;
    }

    /* 表格样式 */
    table {
      width: 100%;
      border-collapse: collapse;
      margin-top: 1rem;
    }

    thead {
      background-color: #f1f1f1;
    }

    th,
    td {
      padding: 12px 16px;
      border-bottom: 1px solid #ddd;
      text-align: left;
      transition: background 0.3s;
    }

    tr:hover {
      background-color: #f9f9f9;
    }

    /* 操作按钮 */
    .btn {
      padding: 6px 12px;
      border-radius: 0.5rem;
      border: none;
      cursor: pointer;
      font-weight: bold;
      transition: all 0.2s ease;
    }

    .btn-delete {
      background: #e53935;
      color: white;
    }

    .btn-edit {
      background: #4CAF50;
      color: white;
    }

    .btn:hover {
      transform: translateY(-2px);
      box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
    }

    /* 表单卡片 */
    .form-card {
      background: #f8f9fa;
      padding: 1.5rem;
      border-radius: 1.2rem;
      margin-top: 2rem;
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
    }

    .form-card h2 {
      margin-top: 0;
      color: #1a73e8;
    }

    label {
      display: block;
      margin: 10px 0 5px;
      font-weight: 500;
    }

    input,
    select {
      width: 100%;
      padding: 10px 12px;
      border: 1px solid #ccc;
      border-radius: 0.8rem;
      font-size: 1rem;
      transition: border-color 0.3s;
    }

    input:focus,
    select:focus {
      border-color: #1a73e8;
      outline: none;
      box-shadow: 0 0 0 3px rgba(26, 115, 232, 0.2);
    }

    button[type="submit"] {
      background: linear-gradient(135deg, #1a73e8, #3f8efc);
      color: white;
      padding: 10px 20px;
      border: none;
      border-radius: 0.8rem;
      font-size: 1rem;
      margin-top: 1.5rem;
      cursor: pointer;
      transition: all 0.3s ease;
    }

    button[type="submit"]:hover {
      transform: translateY(-2px);
      box-shadow: 0 6px 15px rgba(26, 115, 232, 0.3);
    }

    /* 错误提示 */
    #error {
      display: none;
      background: #ffebee;
      color: #d32f2f;
      padding: 12px 16px;
      border-radius: 0.8rem;
      margin-top: 1rem;
      border-left: 4px solid #d32f2f;
      animation: fadeIn 0.3s ease-in-out;
    }

    @keyframes fadeIn {
      from {
        opacity: 0;
        transform: translateY(-10px);
      }
      to {
        opacity: 1;
        transform: translateY(0);
      }
    }

    /* 难度标签 */
    .difficulty-tag {
      display: inline-block;
      padding: 4px 10px;
      border-radius: 1rem;
      font-size: 0.85rem;
      font-weight: 500;
    }

    .difficulty-1 {
      background: #e8f5e9;
      color: #2e7d32;
    }

    .difficulty-2 {
      background: #fff3cd;
      color: #856404;
    }

    .difficulty-3 {
      background: #ffebee;
      color: #c62828;
    }

    /* 响应式设计 */
    @media (max-width: 768px) {
      input,
      select {
        font-size: 0.9rem;
      }

      .btn {
        font-size: 0.85rem;
      }

      .form-card {
        padding: 1rem;
      }
    }
  </style>
</head>
<body>
  <div class="container">
    <a href="index.html" class="back-link">← 返回导航页</a>
    <h1>题目管理</h1>

    <!-- 题目表格 -->
    <table id="question-table">
      <thead>
        <tr>
          <th>ID</th>
          <th>类型</th>
          <th>内容</th>
          <th>A选项</th>
          <th>B选项</th>
          <th>C选项</th>
          <th>答案</th>
          <th>难度</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody id="question-body"></tbody>
    </table>

    <!-- 新增题目表单 -->
    <div class="form-card">
      <h2>新增题目</h2>
      <form id="add-question-form">
        <label>ID:</label>
        <input type="number" id="question-id" placeholder="请输入 ID" required />

        <label>类型:</label>
        <select id="question-type">
          <option value="single_choice">单选题</option>
          <option value="true_false">判断题</option>
        </select>

        <label>内容:</label>
        <input type="text" id="question-content" required />

        <label>A选项:</label>
        <input type="text" id="question-choiceA" required />

        <label>B选项:</label>
        <input type="text" id="question-choiceB" required />

        <label>C选项:</label>
        <input type="text" id="question-choiceC" required />

        <label>答案:</label>
        <select id="question-answer">
          <option value="A">A</option>
          <option value="B">B</option>
          <option value="C">C</option>
        </select>

        <label>难度:</label>
        <select id="question-grade">
          <option value="1">1</option>
          <option value="2">2</option>
          <option value="3">3</option>
        </select>

        <button type="submit">提交</button>
      </form>
    </div>

    <!-- 错误提示 -->
    <p id="error"></p>
  </div>

  <script>
    const SERVER_URL = "http://47.109.75.129:3000/questions";
    const questionBody = document.getElementById("question-body");
    const errorDiv = document.getElementById("error");

    // 类型映射表
    const QUESTION_TYPE_MAP = {
        'single_choice': '单选题',
        'true_false': '判断题'
    };

    // 逆向映射用于回显
    const QUESTION_TYPE_REVERSE_MAP = {
        '单选题': 'single_choice',
        '判断题': 'true_false'
    };

    function getTypeDisplay(type) {
        return QUESTION_TYPE_MAP[type] || type;
    }

    function getTypeValue(display) {
        return QUESTION_TYPE_REVERSE_MAP[display] || display;
    }

    function fetchQuestions() {
        fetch(SERVER_URL)
            .then(response => response.json())
            .then(data => {
                questionBody.innerHTML = "";
                if (data.length === 0) {
                    questionBody.innerHTML = "<tr><td colspan='9'>暂无数据</td></tr>";
                    return;
                }

                data.forEach(item => {
                    const row = document.createElement("tr");
                    row.innerHTML = `
                        <td>${item.id}</td>
                        <td>${getTypeDisplay(item.type)}</td>
                        <td>${item.content}</td>
                        <td>${item.choiceA}</td>
                        <td>${item.choiceB}</td>
                        <td>${item.choiceC}</td>
                        <td>${item.answer}</td>
                        <td><span class="difficulty-tag difficulty-${item.grade}">${item.grade}</span></td>
                        <td>
                            <button class="btn btn-delete" onclick="deleteQuestion(${item.id})">删除</button>
                            <button class="btn btn-edit" onclick="editQuestion(${item.id}, '${item.type}')">编辑</button>
                        </td>
                    `;
                    questionBody.appendChild(row);
                });
            })
            .catch(error => {
                showError("无法加载数据，请检查后端服务");
            });
    }

    document.getElementById("add-question-form").addEventListener("submit", function (e) {
      e.preventDefault();
      const id = document.getElementById("question-id").value;
      const type = document.getElementById("question-type").value;
      const content = document.getElementById("question-content").value;
      const choiceA = document.getElementById("question-choiceA").value;
      const choiceB = document.getElementById("question-choiceB").value;
      const choiceC = document.getElementById("question-choiceC").value;
      const answer = document.getElementById("question-answer").value;
      const grade = document.getElementById("question-grade").value;

      const payload = {
        id: id ? parseInt(id) : undefined,
        type,
        content,
        choiceA,
        choiceB,
        choiceC,
        answer,
        grade
      };

      fetch(SERVER_URL, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(payload)
      })
        .then((response) => {
          if (!response.ok) throw new Error("新增失败");
          return response.json();
        })
        .then(() => {
          document.getElementById("add-question-form").reset();
          fetchQuestions();
        })
        .catch((error) => {
          showError("新增题目失败：" + error.message);
        });
    });

    function deleteQuestion(id) {
      if (!confirm("确定要删除此题目吗？")) return;
      fetch(`${SERVER_URL}/${id}`, {
        method: "DELETE"
      })
        .then((response) => {
          if (!response.ok) throw new Error("删除失败");
          return response.json();
        })
        .then(() => fetchQuestions())
        .catch((error) => {
          showError("删除题目失败：" + error.message);
        });
    }

    function editQuestion(id, rawType) {
        const displayType = getTypeDisplay(rawType);
        const content = prompt("请输入新内容：");
        if (content === null) return;

        const choiceA = prompt("请输入新 A 选项：");
        const choiceB = prompt("请输入新 B 选项：");
        const choiceC = prompt("请输入新 C 选项：");
        const answer = prompt("请输入新答案（A/B/C）：", "A");
        const grade = prompt("请输入新难度等级（1-3）：", "1");
        
        // 弹窗使用中文显示，但提交仍用原始值
        const newType = prompt("请输入新类型（单选题/判断题）", displayType) || displayType;
        const finalType = getTypeValue(newType);

        fetch(`${SERVER_URL}/${id}`, {
            method: "PUT",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({
                content,
                choiceA,
                choiceB,
                choiceC,
                answer,
                grade,
                type: finalType // 提交原始值
            })
        })
            .then(response => {
                if (!response.ok) throw new Error("更新失败");
                return response.json();
            })
            .then(() => fetchQuestions())
            .catch(error => {
                showError("更新题目失败：" + error.message);
            });
    }

    function showError(message) {
      if (message) {
        errorDiv.textContent = message;
        errorDiv.style.display = "block";
      } else {
        errorDiv.textContent = "";
        errorDiv.style.display = "none";
      }
    }

    window.onload = () => {
      fetchQuestions();
      setInterval(fetchQuestions, 10000);
    };
  </script>
</body>
</html>